package org.jeecgframework.web.service.impl;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.jeecgframework.core.util.DateUtils;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.web.service.ZyFactoryRecordServiceI;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.pojo.base.ZyEquipmentSpareEntity;
import org.jeecgframework.web.system.pojo.base.ZyEquipmentTypeEntity;
import org.jeecgframework.web.system.pojo.base.ZyEsItemEntity;
import org.jeecgframework.web.system.pojo.base.ZyFactoryRecordEntity;
import org.jeecgframework.web.system.pojo.base.ZyFileLogEntity;
import org.jeecgframework.web.system.pojo.base.ZyUpFactoryRecordThread;
import org.jeecgframework.web.util.ExcelUtil;
import org.jeecgframework.web.util.ExcelWrite;
import org.jeecgframework.web.util.FileBean;
import org.jeecgframework.web.util.StaticValue;
import org.jeecgframework.web.util.UploadFileUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

@Service("zyFactoryRecordService")
@Transactional
public class ZyFactoryRecordServiceImpl extends CommonServiceImpl implements ZyFactoryRecordServiceI {

	DateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
	
	public <T> void saveFactoryRecordHis(T entity){
		super.save(entity);
	}
	
 	public <T> void delete(T entity) {
 		super.delete(entity);
 		//执行删除操作配置的sql增强
		this.doDelSql((ZyFactoryRecordEntity)entity);
 	}
 	
 	public <T> Serializable save(T entity) {
 		Serializable t = super.save(entity);
 		//执行新增操作配置的sql增强
 		this.doAddSql((ZyFactoryRecordEntity)entity);
 		return t;
 	}
 	
 	public <T> void saveOrUpdate(T entity) {
 		super.saveOrUpdate(entity);
 		//执行更新操作配置的sql增强
 		this.doUpdateSql((ZyFactoryRecordEntity)entity);
 	}
 	
 	/**
	 * 默认按钮-sql增强-新增操作
	 * @param id
	 * @return
	 */
 	public boolean doAddSql(ZyFactoryRecordEntity t){
	 	return true;
 	}
 	/**
	 * 默认按钮-sql增强-更新操作
	 * @param id
	 * @return
	 */
 	public boolean doUpdateSql(ZyFactoryRecordEntity t){
	 	return true;
 	}
 	/**
	 * 默认按钮-sql增强-删除操作
	 * @param id
	 * @return
	 */
 	public boolean doDelSql(ZyFactoryRecordEntity t){
	 	return true;
 	}
 	
 	/**
	 * 替换sql中的变量
	 * @param sql
	 * @return
	 */
 	public String replaceVal(String sql,ZyFactoryRecordEntity t){
 		sql  = sql.replace("#{id}",String.valueOf(t.getId()));
 		sql  = sql.replace("#{search_argument}",String.valueOf(t.getSearchArgument()));
 		sql  = sql.replace("#{sold_to_bp}",String.valueOf(t.getSoldToBp()));
 		sql  = sql.replace("#{sold_to_contact}",String.valueOf(t.getSoldToContact()));
 		sql  = sql.replace("#{item}",String.valueOf(t.getItem()));
 		sql  = sql.replace("#{serial_num}",String.valueOf(t.getSerialNum()));
 		sql  = sql.replace("#{item_desc}",String.valueOf(t.getItemDesc()));
 		sql  = sql.replace("#{alternate_serial_nr}",String.valueOf(t.getAlternateSerialNr()));
 		sql  = sql.replace("#{creation_date}",String.valueOf(t.getCreationDate()));
 		sql  = sql.replace("#{creation_time}",String.valueOf(t.getCreationTime()));
 		sql  = sql.replace("#{serialized_item_group}",String.valueOf(t.getSerializedItemGroup()));
 		sql  = sql.replace("#{sold_to_address}",String.valueOf(t.getSoldToAddress()));
 		sql  = sql.replace("#{warranty}",String.valueOf(t.getWarranty()));
 		sql  = sql.replace("#{ierm_id}",String.valueOf(t.getTermId()));
 		sql  = sql.replace("#{installation_date}",String.valueOf(t.getInstallationDate()));
 		sql  = sql.replace("#{installation_time}",String.valueOf(t.getInstallationTime()));
 		sql  = sql.replace("#{covered_by_contr_enum}",String.valueOf(t.getCoveredByContrEnum()));
 		sql  = sql.replace("#{covered_by_contract}",String.valueOf(t.getCoveredByContract()));
 		sql  = sql.replace("#{revision}",String.valueOf(t.getRevision()));
 		sql  = sql.replace("#{dummy_serial_nr_enum}",String.valueOf(t.getDummySerialNrEnum()));
 		sql  = sql.replace("#{dummy_serial_nr}",String.valueOf(t.getDummySerialNr()));
 		sql  = sql.replace("#{buy_from_bp}",String.valueOf(t.getBuyFromBp()));
 		sql  = sql.replace("#{delivery_date}",String.valueOf(t.getDeliveryDate()));
 		sql  = sql.replace("#{delivery_time}",String.valueOf(t.getDeliveryTime()));
 		sql  = sql.replace("#{prj}",String.valueOf(t.getPrj()));
 		sql  = sql.replace("#{prj_element_activity}",String.valueOf(t.getPrjElementActivity()));
 		sql  = sql.replace("#{sales_order}",String.valueOf(t.getSalesOrder()));
 		sql  = sql.replace("#{sales_order_line}",String.valueOf(t.getSalesOrderLine()));
 		sql  = sql.replace("#{specification_a}",String.valueOf(t.getSpecificationA()));
 		sql  = sql.replace("#{specification_b}",String.valueOf(t.getSpecificationB()));
 		sql  = sql.replace("#{machine}",String.valueOf(t.getMachine()));
 		sql  = sql.replace("#{cluster}",String.valueOf(t.getCluster()));
 		sql  = sql.replace("#{status_enum}",String.valueOf(t.getStatusEnum()));
 		sql  = sql.replace("#{status}",String.valueOf(t.getStatus()));
 		sql  = sql.replace("#{status_date}",String.valueOf(t.getStatusDate()));
 		sql  = sql.replace("#{status_time}",String.valueOf(t.getStatusTime()));
 		sql  = sql.replace("#{top_item}",String.valueOf(t.getTopItem()));
 		sql  = sql.replace("#{top_serial_nr}",String.valueOf(t.getTopSerialNr()));
 		sql  = sql.replace("#{work_site_address}",String.valueOf(t.getWorkSiteAddress()));
 		sql  = sql.replace("#{work_site_info}",String.valueOf(t.getWorkSiteInfo()));
 		sql  = sql.replace("#{contact}",String.valueOf(t.getContact()));
 		sql  = sql.replace("#{service_dept}",String.valueOf(t.getServiceDept()));
 		sql  = sql.replace("#{registration_date}",String.valueOf(t.getRegistrationDate()));
 		sql  = sql.replace("#{registration_time}",String.valueOf(t.getRegistrationTime()));
 		sql  = sql.replace("#{counter_reading}",String.valueOf(t.getCounterReading()));
 		sql  = sql.replace("#{measurement_type}",String.valueOf(t.getMeasurementType()));
 		sql  = sql.replace("#{subcontractor}",String.valueOf(t.getSubcontractor()));
 		sql  = sql.replace("#{ship_from_bp}",String.valueOf(t.getShipFromBp()));
 		sql  = sql.replace("#{ship_from_address}",String.valueOf(t.getShipFromAddress()));
 		sql  = sql.replace("#{lot}",String.valueOf(t.getLot()));
 		sql  = sql.replace("#{manufacturing_date}",String.valueOf(t.getManufacturingDate()));
 		sql  = sql.replace("#{priority}",String.valueOf(t.getPriority()));
 		sql  = sql.replace("#{log_comp}",String.valueOf(t.getLogComp()));
 		sql  = sql.replace("#{phys_comp}",String.valueOf(t.getPhysComp()));
 		sql  = sql.replace("#{is_sustainable}",String.valueOf(t.getIsSustainable()));
 		sql  = sql.replace("#{is_deletable}",String.valueOf(t.getIsDeletable()));
 		sql  = sql.replace("#{create_name}",String.valueOf(t.getCreateName()));
 		sql  = sql.replace("#{create_by}",String.valueOf(t.getCreateBy()));
 		sql  = sql.replace("#{update_name}",String.valueOf(t.getUpdateName()));
 		sql  = sql.replace("#{update_by}",String.valueOf(t.getUpdateBy()));
 		sql  = sql.replace("#{create_date}",String.valueOf(t.getCreateDate()));
 		sql  = sql.replace("#{update_date}",String.valueOf(t.getUpdateDate()));
 		sql  = sql.replace("#{UUID}",UUID.randomUUID().toString());
 		return sql;
 	}
 	
 	/**
	 * @Description 解析EXCEL
	 * @param HttpServletRequest 通过前台请求获得文件流
	 */
	public List<Map<String, Object>> parseExcel(HttpServletRequest req,AjaxJson j) {
		List<Map<String, Object>> factroyMapList = new ArrayList<Map<String, Object>>();
		try {
			String filePath = req.getParameter("filePath");
			j.setObj(filePath);
			List<Map<String, Object>> mapList = ExcelUtil.analyzeExcel(filePath, "1");
			for (int r = 1;r < mapList.size(); r++) {
				Map<String, Object> rowMap = mapList.get(r);
				Map<String, Object> map = new HashMap<String, Object>();
				String item = rowMap.get("3").toString();
				map.put("item", item);
				map.put("sn", rowMap.get("4").toString());
				map.put("topItemSn", rowMap.get("36").toString());
				map.put("sendDate", DateUtils.str2Date(rowMap.get("21").toString(), DateUtils.sdf_date_1));
				map.put("installDate", DateUtils.str2Date(rowMap.get("13").toString(), DateUtils.sdf_date_1));
				map.put("serverState", StaticValue.DIC_SERVER_STATE_1001);
				map.put("isNormal", "0");
				map.put("bpNo", rowMap.get("1").toString());
				map.put("isServicing", "0");
				map.put("isSpare", isSpare(item));
				factroyMapList.add(map);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return factroyMapList;
	}
	
	@Override
	public String checkSnRepeat(List<Map<String, Object>> factroyMapList,List<Map<String, Object>> snMapList, int begin, int end) {
		System.out.println("beginR:" + begin);
		System.out.println("endR:" + end);
		String repeatSn = "";
		List<Map<String, Object>> esMapList = new ArrayList<Map<String,Object>>();
		for(int i = begin;i <= end;i++ ){
			boolean flag = true;
			for(int c = 0;c < snMapList.size();c++){
				if(factroyMapList.get(i).get("sn").equals(snMapList.get(c).get("sn"))){
					repeatSn += factroyMapList.get(i).get("sn").toString() + ",";
					flag = false;
					break;
				}
			}
			if(flag){
				esMapList.add(factroyMapList.get(i));
			}
		}
		saveEquipmentSpares(esMapList);
		return repeatSn = StringUtil.isNotEmpty(repeatSn) ? repeatSn.substring(0,repeatSn.length()-1) : repeatSn;
	}
	
	
	private void saveEquipmentSpares(List<Map<String, Object>> esMapList){
		List<ZyEquipmentSpareEntity> esList = new ArrayList<ZyEquipmentSpareEntity>();
		ZyEquipmentSpareEntity zyEquipmentSpareEntity = null;
		List<ZyEsItemEntity> esItems = super.getList(ZyEsItemEntity.class);
		Calendar cl = Calendar.getInstance();
		List<TSDepart> tsDeparts = super.getList(TSDepart.class);
		for (Map<String, Object> esMap : esMapList) {
			if(!esMap.get("sn").toString().equals("")){
				zyEquipmentSpareEntity = new ZyEquipmentSpareEntity();
				zyEquipmentSpareEntity.setSn(esMap.get("sn").toString());
				zyEquipmentSpareEntity.setItem(esMap.get("item").toString());
				for (ZyEsItemEntity esItem : esItems) {
					if(esItem.getItem().equals(esMap.get("item").toString())){
						zyEquipmentSpareEntity.setType(esItem.getType());
						break;
					}
				}
				zyEquipmentSpareEntity.setTopItemSn(esMap.get("topItemSn").toString());
				zyEquipmentSpareEntity.setSendDate(null != esMap.get("sendDate") ? (Date)esMap.get("sendDate") : null);
				zyEquipmentSpareEntity.setInstallDate(null != esMap.get("installDate") ? (Date)esMap.get("installDate") : null);
				if(null != zyEquipmentSpareEntity.getInstallDate()){
					cl.setTime(zyEquipmentSpareEntity.getInstallDate());
					cl.add(Calendar.YEAR, 2);
					zyEquipmentSpareEntity.setRepairEndDate(cl.getTime());//保修截止日期是安装日期+2年
				}
				zyEquipmentSpareEntity.setServerState(StaticValue.DIC_SERVER_STATE_1001);
				zyEquipmentSpareEntity.setIsNormal("0");
				zyEquipmentSpareEntity.setBpNo(esMap.get("bpNo").toString());
				if(null != esMap.get("bpNo").toString()){//根据bpno查询对应机构，如果查出多个 则取第一个（amy 说的）
					for(TSDepart depart: tsDeparts){
						if(depart.getBpCode().equals(zyEquipmentSpareEntity.getBpNo())){
							zyEquipmentSpareEntity.setTsDepart(depart);//根据BPno反向设置 所属机构字段
							break;
						}
					}
				}
				zyEquipmentSpareEntity.setIsServicing("0");
				zyEquipmentSpareEntity.setIsSpare(null != esMap.get("isSpare") ? (Boolean)esMap.get("isSpare") : null);
				zyEquipmentSpareEntity.setLaserReconstruction("0");
				zyEquipmentSpareEntity.setIsHadInspection("0");
				esList.add(zyEquipmentSpareEntity);
			}
		}
		if(esList != null){
			super.batchSave(esList);
		}
	}
	
	@Override
	public void readExcel(String filePath) {
		File excelFile = new File(filePath);
		FileInputStream is;
		try {
			is = new FileInputStream(excelFile);
			XSSFWorkbook xssfWb = new XSSFWorkbook(is);
			XSSFSheet sheet = xssfWb.getSheetAt(0);
			int maxUnit = 2000;//每N 条 启动一个线程
    		int countRow = sheet.getPhysicalNumberOfRows();
    		int threadC = countRow / maxUnit;
    		int points = countRow % maxUnit;
    		if(threadC > 0){
    			if(points > 0){
    				threadC = threadC + 1;
    			}
    		}else{
    			threadC = 1;
    		}
    		super.executeSql("DELETE FROM zy_factory_record ");//先删除 所有 导入出厂记录
    		System.out.println("启动线程数量:" + threadC);
    		for (int i = 0; i < threadC; i++) {
    			int beginR = i == 0 ? 1 : i * maxUnit + 1;
				int endR = i == (threadC -1 ) ? countRow : beginR + maxUnit - 1 ;
				ZyUpFactoryRecordThread upEuqipmentThread = new ZyUpFactoryRecordThread(beginR, endR, sheet);
				upEuqipmentThread.start();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	private boolean isSpare(String item){
		String typeDesc="";
		ZyEsItemEntity zyEsItem = findUniqueByProperty(ZyEsItemEntity.class, "item", item);
		ZyEquipmentTypeEntity zyEquipmentType = null;
		if(null != zyEsItem){
			zyEquipmentType = findUniqueByProperty(ZyEquipmentTypeEntity.class, "id", zyEsItem.getType().getId());
			for(int i=0;i<4;i++){
				if(null != zyEquipmentType.getEquipmentType()){
					zyEquipmentType = findUniqueByProperty(ZyEquipmentTypeEntity.class, "id", zyEquipmentType.getEquipmentType().getId());
				}else{
					typeDesc = zyEquipmentType.getTypeDesc();
					break;
				}
			}
		}
		if(typeDesc.equals("设备")){
			return false;
		}
		return true;
	}
	
}